import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    let token = request.headers.token;
    if (token) {
      // 解析token
      let data = new JwtService().decode(token);

      let now = new Date().getTime() / 1000;
      if (now > Number(data.iat) + 7200) {
        throw new HttpException('token已过期', 202);
      }

      if (data.id) {
        request.uid = data.id;
        return true;
      } else {
        throw new HttpException('token无效', 202);
      }
    } else {
      throw new HttpException('请登录', 202);
    }
  }
}
